<?php

namespace Base\NewsBundle\Repository;

use Doctrine\ORM\EntityRepository;

class NewsRepository extends EntityRepository
{
    public function getNews()
    {
        $q = $this->createQueryBuilder('n')
             ->addSelect('u.username AS u_username')
             ->addSelect('m.name AS m_name')
             ->innerJoin('n.modification_user_id', 'u')
             ->leftJoin('n.media_id', 'm')
             ->where('n.is_published = 1')
             ->orderBy('n.updatedAt', 'DESC')
             ->getQuery();

        return $q;
    }

    public function getCurrentNews($slug)
    {
        $q = $this->createQueryBuilder('n')
                    ->addSelect('u.username AS u_username')
                    ->addSelect('m.name AS m_name')
                    ->innerJoin('n.modification_user_id', 'u')
                    ->leftJoin('n.media_id', 'm')
                    ->where('n.is_published = 1')
                    ->andWhere('n.slug = :slug')
                    ->setParameter('slug', $slug)
                    ->orderBy('n.updatedAt', 'DESC')
                    ->getQuery();

        return $q;
    }

    public function findAllOrderedByUpdatedAt($limit = 10)
    {
        $query = $this->createQueryBuilder('n')
                      ->addSelect('u.username AS u_username')
                      ->addSelect('m.name AS m_name')
                      ->innerJoin('n.modification_user_id', 'u')
                      ->leftJoin('n.media_id', 'm')
                      ->where('n.is_published = :is_published')
                      ->orderBy('n.updatedAt', 'DESC')
                      ->setMaxResults($limit)
                      ->setParameter('is_published', '1')
                      ->getQuery();

        try {
            return $query->getResult($query::HYDRATE_SCALAR);
        } catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }
}

?>
